package com.zzy.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzy.common.core.redis.RedisCache;
import com.zzy.common.utils.guanmai.GuanmaiCommon;
import com.zzy.system.domain.*;
import com.zzy.system.mapper.DetectReportMapper;
import com.zzy.system.mapper.DetectReportSpusMapper;
import com.zzy.system.mapper.OutStockSheetOrderMapper;
import com.zzy.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DetectReportServiceImpl extends ServiceImpl<DetectReportMapper, DetectReport> implements IDetectReportService {
    private static final Logger log = LoggerFactory.getLogger(DetectReportServiceImpl.class);

    // 注入 RedisCache 对象
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IDetectReportPicturesService iDetectReportPicturesService;
    @Autowired
    private IDetectReportSpusService iDetectReportSpusService;
    @Autowired
    private IDetectReportSpusBatchService  iDetectReportSpusBatchService;
    // 注入配置文件中的观麦令牌在 Redis 中的键名
    @Value("${api.guanmaiTokenKey}")
    private String guanmaiTokenKey;
    @Autowired
    private DetectReportSpusMapper detectReportSpusMapper;
    // 注入配置文件中的观麦接口 URL


    //请求观麦 获取订单集合
    @Override
    @Transactional
    public String getGuanmaiProductTraceList(Integer status, String startDate, String endDate, Integer offset, Integer limit) throws Exception {
        List<DetectReport> allDetectReport=new ArrayList<>();
        limit=100;
        while (true) {
            Map<String, Object> paramMap = new HashMap<>();
            // 获取今天的日期
            LocalDate today = LocalDate.now();
            // 获取7天前的日期
            LocalDate sevenDaysAgo = today.minusDays(30);

            // 设置开始日期参数
            paramMap.put("begin_time", startDate);
            // 设置截止日期参数
            paramMap.put("end_time", endDate);
            //检测状态 1有效 2失效
            paramMap.put("status", 1);
            // 设置分页offset参数（默认值为0，可按需不传该参数或者修改值）
            paramMap.put("offset", offset);
            // 设置分页limit参数（默认值为100，取值范围<=100，可按需不传该参数或者修改值）
            paramMap.put("limit", limit);
            //报告类型 固定 6
            paramMap.put("report_type", 6);
            //
            //查询类型 1 按 上传日期 / 2 按检测日期
            paramMap.put("query_type", 1);

            //请求观麦 获取订单列表
            String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/trace/detect_report/list/1.0");
            JSONObject reponseJson = JSONObject.parseObject(reponse);
            if (reponseJson.getInteger("code") == 1002) {
                redisCache.deleteObject(guanmaiTokenKey);
                GuanmaiCommon.getGuanmaiToken();
                continue;
            }
            if (reponseJson.get("code").toString().equals("0")) {
                JSONArray jsonArray = reponseJson.getJSONArray("data");
                if (jsonArray != null) {
                    // 将当前页的数据解析并添加到总的结果列表中
                    List<DetectReport> detectReports = jsonArray.toJavaList(DetectReport.class);
                    allDetectReport.addAll(detectReports);
                    // 如果返回的数据条数等于每页显示的数量，说明可能还有更多数据，继续查询下一页
                    if (jsonArray.size() == limit) {
                        offset += limit; // 页码增加，指向下一页
                        continue;
                    } else {
                        // 如果返回的数据条数小于每页显示的数量，说明已经查询完所有数据，结束循环
                        break;
                    }
                }
            } else {
                // 如果接口返回的code不是0，表示请求出现问题，这里可以根据实际情况进行错误处理
                System.out.println("请求出现问题，错误信息：" + reponseJson.get("msg"));
                break;
            }

        }

        QueryWrapper<DetectReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("detect_report_id", 0);
        List<DetectReport> detectReports = this.list(queryWrapper);
        for(DetectReport detectReport : allDetectReport) {
            if(filterIshaveReport(detectReports,detectReport.getReportId())){
                continue;
            }
            getReportDetail(detectReport.getReportId().toString());
        }
        return "";
    }
    public Boolean filterIshaveReport(List<DetectReport>detectReports,Integer reportId){
        // 使用Stream API进行筛选操作
        Optional<DetectReport> firstMatch = detectReports.stream()
                .filter(detectReport -> reportId == detectReport.getReportId())
                // 查找第一个匹配的元素
                .findFirst();

        // 匹配到返回true
        return firstMatch.isPresent();
    }


    public void getReportDetail(String reportId) throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        // 设置查询order_id
        paramMap.put("r_id", reportId);
        //请求观麦 获取订单列表
        String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/trace/detect_report/get/1.0");
        JSONObject reponseJson = JSONObject.parseObject(reponse);
        if (reponseJson.getInteger("code") == 1002) {
            redisCache.deleteObject(guanmaiTokenKey);
            GuanmaiCommon.getGuanmaiToken();
        }
        if (reponseJson.get("code").toString().equals("0")) {
            JSONObject jsonObject = reponseJson.getJSONObject("data");
            DetectReport detectReport = JSON.parseObject(jsonObject.toString(), DetectReport.class);
            this.save(detectReport);
            if (detectReport != null && !detectReport.getPictures().isEmpty()) {
                detectReport.getPictures().forEach(detail -> detail.setReportId(reportId));
                iDetectReportPicturesService.saveReportPicturessList(detectReport.getPictures());
            }
            if (detectReport != null && !detectReport.getSpus().isEmpty()) {
                iDetectReportSpusService.saveReportSpusList(detectReport.getSpus());
                for (DetectReportSpus detectReportSpus : detectReport.getSpus()) {
                    if(detectReportSpus.getDetectReportSpusBatchs()!=null){
                        detectReportSpus.getDetectReportSpusBatchs().forEach(detail -> detail.setDetailId(detectReportSpus.getId()));
                        iDetectReportSpusBatchService.saveReportSpusBatchList(detectReportSpus.getDetectReportSpusBatchs());
                    }

                }
            }


        }
    }



}